//sqlite
const Database = require('better-sqlite3');
const { app } = require('electron');
import { ipcMain } from 'electron'
import log from 'electron-log/main';
import { join } from 'path'
//@ts-nocheck






function initSql() {


    // 获取用户数据目录路径
    const userDataPath = app.getPath('userData');
    const dbPath = join(userDataPath, 'test.db');
    const db = new Database(dbPath)


    // 检查表中是否存在某列的函数
    function columnExists(tableName, columnName) {
        const sql = `PRAGMA table_info(${tableName})`;
        const rows = db.prepare(sql).all();
        return rows.some(row => row.name === columnName);
    }

    // 添加列到表中的函数
    function addColumnIfNotExists(tableName, columnName, columnType) {
        if (!columnExists(tableName, columnName)) {
            const sql = `ALTER TABLE ${tableName} ADD COLUMN ${columnName} ${columnType}`;
            db.prepare(sql).run();
           // console.log(`列 "${columnName}" 已成功添加到表 "${tableName}"`);
           // console.log(`列 "${columnName}" add success "${tableName}"`);

        } else {
            //console.log(`列 "${columnName}" has in "${tableName}" `);
        }
    }


    //离线订单明细表
    db.prepare(`
    CREATE TABLE IF NOT EXISTS offline_order (
      offineID TEXT PRIMARY KEY,
      saleOrganizationID TEXT NOT NULL,
      saleOrganizationName TEXT,
      shopID INTEGER NOT NULL,
      shopCode INTEGER NOT NULL,
      shopName TEXT NOT NULL,
      priceSchemesID INTEGER NOT NULL,
      originalAmount TEXT NOT NULL,
      receivableAmount TEXT NOT NULL,
      discountAmount TEXT NOT NULL,
      goodsQuantity INTEGER NOT NULL,
      orderTime TEXT NOT NULL,
      orderPayDto TEXT NOT NULL,
      orderDetailAddDtos TEXT NOT NULL,
      memberCouponPOSDtos TEXT NOT NULL,
      priceType TEXT NOT NULL,
      priceTypeText TEXT NOT NULL
    )
    `).run();
    // 检查并添加列 (如果不存在saleOrganizationName列，则添加)
    addColumnIfNotExists('offline_order', 'saleOrganizationName', 'TEXT');

    //插入离线订单
    ipcMain.on('insert-order', (_, { offineID, saleOrganizationID, saleOrganizationName, shopID, shopCode, shopName, priceSchemesID, originalAmount, receivableAmount, discountAmount, goodsQuantity, orderTime, orderPayDto, orderDetailAddDtos, memberCouponPOSDtos, priceType, priceTypeText }) => {
        // console.log('insert order~')
        // console.log({ offineID, saleOrganizationID, shopID,shopCode, shopName, priceSchemesID, originalAmount, receivableAmount, discountAmount, goodsQuantity, orderTime, orderPayDto, orderDetailAddDtos, memberCouponPOSDtos, priceType, priceTypeText })
        const prepare = db.prepare("INSERT INTO offline_order (offineID,saleOrganizationID,saleOrganizationName,shopID,shopCode, shopName, priceSchemesID, originalAmount,receivableAmount,discountAmount,goodsQuantity,orderTime, orderPayDto,orderDetailAddDtos,memberCouponPOSDtos,priceType,priceTypeText) VALUES (?,?, ?, ?, ?, ?, ?,?,?,?,?,?,?,?,?,?,?)");
        prepare.run(offineID, saleOrganizationID, saleOrganizationName, shopID, shopCode, shopName, priceSchemesID, originalAmount, receivableAmount, discountAmount, goodsQuantity, orderTime, orderPayDto, orderDetailAddDtos, memberCouponPOSDtos, priceType, priceTypeText)
    })

    //查询离线订单
    ipcMain.handle('select-order', (_, { startTime, endTime, offineID }) => {
        // 构建 SQL 查询语句
        let queryStr = "SELECT * FROM offline_order WHERE 1=1";
        const params = [];

        // 添加时间范围条件
        if (startTime && endTime) {
            queryStr += " AND orderTime BETWEEN ? AND ?";
            // @ts-ignore
            params.push(startTime, endTime);
        }

        // 添加 offineID 条件
        if (offineID) {
            queryStr += " AND offineID LIKE ?";
            // @ts-ignore
            params.push(`%${offineID}%`);
        }

        // 添加排序条件
        queryStr += " ORDER BY orderTime DESC";

        // 执行查询
        const rows = db.prepare(queryStr).all(params);
        return rows;
    })



    // 监听删除订单的事件
    ipcMain.on('delete-order', (_, offineID) => {
        //console.log(offineID)
        try {
            // 准备 SQL 删除语句
            const prepare = db.prepare("DELETE FROM offline_order WHERE offineID = ?");
            const result = prepare.run(offineID); // 执行删除操作
            // 检查是否成功删除
            if (result.changes > 0) {
                log.info(`Order with offineID: ${offineID} deleted successfully`);
            } else {
                log.warn(`No order found with offineID: ${offineID}`);
            }
        } catch (error) {
            log.error(`Error deleting order with offineID: ${offineID}`, error);
        }
    });

}




export {
    initSql
} 
